//
//  ClearCaches.m
//  自封装头文件
//
//  Created by dllo on 15/10/29.
//  Copyright © 2015年 Wang Jianwei. All rights reserved.
//

#import "ClearCaches.h"

@implementation ClearCaches
+ (long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil] fileSize];
    }
    return 0;
}
+ (NSString *)folderSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }
    NSEnumerator *enumerator = [[manager subpathsAtPath:path]objectEnumerator];
    NSString *fileName = [NSString string];
    float folderSize = 0;
    while ((fileName = [enumerator nextObject]) != nil) {
        NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:absolutePath];
    }
    NSString *string = [NSString stringWithFormat:@"%.2fMB", folderSize / (1024.0 * 1024.0)];
    return string;
}
+ (NSString *)clearCaches
{
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray *fileNameArray = [manager subpathsAtPath:path];
        for (NSString *fileName in fileNameArray) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
    
    return [self folderSizeAtPath:path];
}

@end
